package com.firefly.dao.configure;

import com.firefly.dao.util.FireflyRedisCacheManager;
import com.firefly.util.configure.SpringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @description: redis 缓存配置
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2023/4/26
 **/
@Configuration
public class RedisCacheConfig extends CachingConfigurerSupport {
    @Resource
    private RedisTemplate redisTemplate;
    @Value("spring.cache.prefix")
    private String prefix;
     /**
     * 配置cacheManage  使用 RedisTemplate 的配置信息
     */
    @Bean
    public CacheManager cacheManager() {
        if (null == redisTemplate) {
            throw new RuntimeException("需要配置redis");
        }
        RedisConnectionFactory connectionFactory = redisTemplate.getConnectionFactory();
        if (null == connectionFactory) {
            throw new RuntimeException("需要配置redis的 connectionFactory ");
        }
        // 基本配置
        RedisCacheConfiguration defaultCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                // 设置key为String
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getStringSerializer()))
                // 设置value 为自动转Json的Object
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))
                // 不缓存null
                .disableCachingNullValues()
                // 前缀。用来区分不同的项目
                .prefixCacheNameWith(prefix.concat("-"))
                // 缓存数据保存1小时 （默认）
                .entryTtl(Duration.ofHours(1));
        return new FireflyRedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory), defaultCacheConfiguration);
    }
}
